package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.common.ObjectUtil;
import com.shop.common.result.Result;
import com.shop.common.result.util.ResultModel;
import com.shop.dto.factory.SelectAllDistrictDto;
import com.shop.entity.DistrictDo;
import com.shop.mapper.DistrictDoMapper;
import com.shop.service.DistrictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 地区表 服务实现类
 * </p>
 *
 * @author 靳 旺
 * @since 2021-01-29
 */
@Slf4j
@Service
public class DistrictServiceImpl extends ServiceImpl<DistrictDoMapper, DistrictDo> implements DistrictService {

    @Override
    public ResultModel selectAllDistrict() throws Exception {
        List<DistrictDo> districtDos = baseMapper.selectList(new QueryWrapper<>());
        List<SelectAllDistrictDto> dos = new ArrayList<>();
       List<DistrictDo> item = districtDos.stream().filter(k ->
              k.getPid() != null &&  k.getPid() != 0
       ).collect(Collectors.toList());
        Map<Long,List<DistrictDo>> districtDoList = item.stream().collect(Collectors.groupingBy(DistrictDo::getPid));
        districtDos.forEach( k ->{
            if ( k.getPid() != null && k.getPid() == 0){
                SelectAllDistrictDto selectAllDistrictDto = new SelectAllDistrictDto();
                ObjectUtil.annotationToObject(k,selectAllDistrictDto);
                selectAllDistrictDto.setDistrictDos(districtDoList.get(k.getPkDistrictId()));
                dos.add(selectAllDistrictDto);
            }
        });
        return Result.successResultModel(dos);
    }
}
